# encoding:utf-8
from pony.orm import *
import os

def get_home():
    home = os.environ['HOME'] + "/.ssh_tool"
    if not os.path.exists(home):
        os.mkdir(home)
    return home

db_path=get_home()+"/db"

first_time=not os.path.exists(db_path)


def get_keyhome():
    home = get_home()
    key_home = home + "/keys/"

    if not os.path.exists(key_home):
        os.mkdir(key_home)

    return key_home


db = Database('sqlite', db_path, create_db=True)


class Group(db.Entity):
    name = Required(unicode, 20,unique=True)
    desc = Optional(unicode, 20,nullable=True)
    server = Set("Server")


class Key(db.Entity):
    name = Required(unicode, 20,unique=True)
    path = Required(unicode, 100)
    desc = Optional(unicode, 20,nullable=True)
    server = Set("Server")


class Server(db.Entity):
    name = Required(unicode, 20,unique=True)
    host = Required(unicode, 20)
    user = Required(unicode, 20)
    passwd = Optional(unicode, 50,nullable=True)
    port = Required(int)
    type = Required(unicode, 20)
    desc = Optional(unicode, 20,nullable=True)
    key = Optional(Key, nullable=True)
    group = Required(Group)

db.generate_mapping(create_tables=True)
# sql_debug(True)

@db_session
def init():
    Group(name="default")

if first_time:
    init()
